<?php
namespace app\admin\controller;

use thinkless\common\AdminController;
use exception\FriendlyException;
use app\admin\model\AdminModel;
use app\admin\model\AdminPermissionModel;
use app\admin\model\ConfigModel;
use app\admin\service\AdminService;
use think\facade\Config;
use util\PasswordHash;
use util\Tree;
use think\facade\Cookie;
use think\facade\Session;
use util\RandomUtil;
use util\SqlUtil;

class Index extends AdminController {

    /**
     * 首页框架
     */
    public function index() {
        $menus = (new AdminPermissionModel())->where(['type' => 'menu', 'is_show' => 1])->select()->toArray();
        foreach($menus as &$menu) {
            $menu['isOpen'] = true;
            $menu['text'] = $menu['name'];
            $menu['targetType'] = "iframe-tab";
            $menu['url'] = $menu['path'];
            $menu['targetType'] = $menu['target'];
        }
        $menus = Tree::arrayToTree($menus);
        $admin = $this->getCurrentUser();
        return view('/template/framework', [
            'title' => (new ConfigModel())->getValueByKey('backend_title'),
            'admin' => $admin,
            'menus' => $menus
        ]);
    }

    /**
     * 首页
     */
    public function dashbord() {
        return view();
    }

    /**
     * 登录
     */
    public function login() {
        if($this->isApi()) {
            $username = base64_decode(input('post.username', ''));
            $password = base64_decode(input('post.password', ''));
            $captcha = input('post.captcha', '');
            $rememberMe = input('post.remember', false);
            $admin = (new AdminModel)->getByKey('username', $username);
            if (empty($admin)) throw new FriendlyException('未找到用户');
            if(Config::get('security.use_captcha')) {
                if(!captcha_check($captcha)) throw new FriendlyException('验证码有误');
            }
            if(!PasswordHash::check($admin['password'], $password, $admin['salt'])) {
                throw new FriendlyException('密码错误');
            }
            if($admin['status'] == AdminModel::STATUS_LIZHI) {
                throw new FriendlyException('用户已离职');
            }
            $authenticate = [
                'id' => $admin['id']
            ];
            $token = RandomUtil::uuid();
            $admin->save([
                'login_token' => $token,
                'last_login_ip' => request()->ip(),
                'last_login_time' => SqlUtil::datetime(),
            ]);
            $save = json_encode($authenticate, JSON_UNESCAPED_UNICODE);
            Session::set(Config::get('security.session_key'), $save);
            if($rememberMe) {
                $keeptime = 86400 * 7;
                $expiretime = time() + $keeptime;
                $key = md5(md5($admin['id']) . md5($keeptime) . md5($expiretime) . $token . Config::get('security.cookie_token', ''));
                $data = [$admin['id'], $keeptime, $expiretime, $key];
                Cookie::set(Config::get('security.cookie_key'), implode('|', $data), $keeptime);
            }
            return $this->jSuccess($save);
        } else {
            return view('login', [
                'use_captcha' => Config::get('security.use_captcha') ? 'true' : 'false',
                'login_path' => Config::get('security.login_path', ''),
            ]);
        }
    }

    public function info() {
        phpinfo();
    }

    /**
     * 登出
     */
    public function logout() {
        Session::delete(Config::get('security.session_key'));
        Cookie::delete(Config::get('security.cookie_key'));
        return redirect('/admin/index/login');
    }

    /**
     * 个人中心
     */
    public function profile() {
        if($this->isApi()) {
            $user = $this->getCurrentUser();
            return $this->jSuccess($user);
        } else {
            return view();
        }
    }

    /**
     * 修改密码
     */
    public function changePassword() {
        $oldpassword = base64_decode(input('post.oldpassword', ''));
        $newpassword = base64_decode(input('post.newpassword', ''));
        $newpassword2 = base64_decode(input('post.newpassword2', ''));
        if($newpassword != $newpassword2) throw new FriendlyException("两次输入新密码不相同");
        if(strlen($newpassword)<6) throw new FriendlyException("密码长度需大于6位");
        $uid = $this->getCurrentUserId();
        $admin = (new AdminModel)->mustFindOne($uid);
        if(!PasswordHash::check($admin['password'], $oldpassword, $admin['salt'])) {
            throw new FriendlyException('旧密码错误');
        }
        (new AdminService)->updatePassword($admin, $newpassword);
        Session::clear(Config::get('security.session_key'));
        Cookie::delete(Config::get('security.cookie_key'));
        return $this->jSuccess();
    }
}
